<?php
// 设置SSE响应头
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

// 设置跨域访问头
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');

// 处理 OPTIONS 预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 禁用输出缓冲
if (ob_get_level()) {
    ob_end_clean();
}

// 设置脚本执行时间无限
set_time_limit(0);

// 读取audio.js文件内容
$audioFile = __DIR__ . '/example/js/audio2.js';
if (!file_exists($audioFile)) {
    echo "event: error\n";
    echo "data: {\"code\": 1, \"msg\": \"Audio file not found\"}\n\n";
    exit;
}

// 读取并解析音频数据
$content = file_get_contents($audioFile);
// 提取音频数据数组
if (preg_match('/const audioData = (\[.*?\]);/s', $content, $matches)) {
    $audioData = json_decode($matches[1], true);

    if ($audioData === null) {
        echo "event: error\n";
        echo "data: {\"code\": 1, \"msg\": \"Failed to parse audio data\"}\n\n";
        exit;
    }

    // 每200毫秒发送一个音频块
    $interval = 200000; // 200毫秒 = 200000微秒

    // 发送每个音频数据块
    foreach ($audioData as $index => $chunk) {
        // 检查是否是音频流数据 (frameType = "1")
        if (isset($chunk['frameType']) && $chunk['frameType'] === "1") {
            // 发送数据块
            echo "data: " . json_encode($chunk) . "\n\n";

            // 刷新输出缓冲区
            if (ob_get_level()) {
                ob_flush();
            }
            flush();

            // 检查连接是否断开
            if (connection_aborted()) {
                break;
            }

            // 延迟发送下一个数据块
            usleep($interval);
        } else if (isset($chunk['frameType']) && $chunk['frameType'] === "0") {
            // 控制帧,继续发送不中断
            echo "data: " . json_encode($chunk) . "\n\n";

            if (ob_get_level()) {
                ob_flush();
            }
            flush();

            // 检查连接是否断开
            if (connection_aborted()) {
                break;
            }

            // 延迟发送下一个数据块
            usleep($interval);
        } else if (isset($chunk['data']) && isset($chunk['workId'])) {
            // 发送初始数据帧
            echo "data: " . json_encode($chunk) . "\n\n";

            if (ob_get_level()) {
                ob_flush();
            }
            flush();

            // 延迟发送下一个数据块
            usleep($interval);
        }
    }

    // 发送结束事件
    // echo "event: end\n";
    // echo "data: {\"code\": 0, \"msg\": \"Stream ended\"}\n\n";

    if (ob_get_level()) {
        ob_flush();
    }
    flush();
} else {
    echo "event: error\n";
    echo "data: {\"code\": 1, \"msg\": \"Failed to extract audio data\"}\n\n";
}

exit;
